package cn.rengy.web.framework.sys.area;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

import cn.rengy.lang.ResultEntity;
import cn.rengy.web.framework.sql.Dao;

@Controller
@RequestMapping
public class AreaController {
	
	@Autowired
	private AreaService areaService;
	@Autowired
	private Dao dao;
	@RequestMapping(value="/authenticated/area/reSetTreeid")
	@ResponseBody
    public ResultEntity<?> reSetTreeid(){
		areaService.reSetTreeid();
		return ResultEntity.ok();
	}
	/**
	 * 生成area.js
	 * id是adcode，tree_id 是额外属性
	 */
	@RequestMapping(value="/authenticated/area/createjs")
	@ResponseBody
	public void createjs(){
		List<Map<String,Object>> list=this.dao.queryForList("select adcode id, tree_id,name text from sys_area where level=1");
		for(Map<String,Object> province:list){
			Integer province_adcode=(Integer)province.get("id");
			String tree_id=(String)province.remove("tree_id");
			Map<String,Object> at=new HashMap<String,Object>();
			at.put("tree_id", tree_id);
			province.put("attributes", at);
			List<Map<String,Object>> cityList=this.dao.queryForList("select adcode id, tree_id,name text from sys_area where parent_adcode=?",province_adcode);
			if(cityList!=null&&cityList.size()>0){
				province.put("state", "closed"); 
				province.put("children", cityList);
				for(Map<String,Object> city:cityList){
					Integer city_adcode=(Integer)city.get("id");
					String city_tree_id=(String)city.remove("tree_id");
					Map<String,Object> bt=new HashMap<String,Object>();
					bt.put("tree_id", city_tree_id);
					city.put("attributes", bt);
					
					List<Map<String,Object>> districtList=this.dao.queryForList("select adcode id, tree_id,name text  from sys_area where parent_adcode=?",city_adcode);
					if(districtList!=null&&districtList.size()>0){
						city.put("state", "closed"); 
						city.put("children", districtList);
						
						for(Map<String,Object> dist:districtList){
							Integer dist_adcode=(Integer)dist.get("id");
							String dist_tree_id=(String)dist.remove("tree_id");
							Map<String,Object> ct=new HashMap<String,Object>();
							ct.put("tree_id", dist_tree_id);
							dist.put("attributes", ct);
							
						}
					}
				}
			}
		}
		String s=JSONArray.toJSONString(list);
		try {
			FileUtils.writeStringToFile(new File("D:/area.js"), "areaData="+s+";");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
